#install packages
library(panelView)
library(zoo)
library(synthdid)
library(fect)
library(ggplot2)
source("staggered_synth.R")
#prepare data
laws = read.csv("statelaws2024.csv")
turnout = read.csv("stateturnout2024.csv")
laws = laws[laws$State!="",]
results <- list()

for (i in 1:nrow(laws)) {
  for (j in 2:ncol(laws)) { 
    if (!is.na(laws[i, j])) {
      if (laws[i, j] == "X") {
        results <- c(results, list(data.frame(STATE = laws$State[i], YEAR = colnames(laws)[j], Law = TRUE)))
      }else {
        results <- c(results, list(data.frame(STATE = laws$State[i], YEAR = colnames(laws)[j], Law = FALSE)))
      }
    }else {
      results <- c(results, list(data.frame(STATE = laws$State[i], YEAR = colnames(laws)[j], Law = FALSE)))
    }
  }
}
laws <- do.call(rbind, results)
laws$YEAR <-substring(laws$YEAR,2,10000)

data = merge(laws,turnout,by=c("STATE","YEAR"))
data = data[data$YEAR != 1982&data$YEAR != 1980,]
data = data[!(data$STATE %in%c("Texas", "Virginia")),]
data$Y[data$YEAR <= 2020] = as.numeric(gsub(",","",data[data$YEAR <= 2020, ]$VOTE_FOR_HIGHEST_OFFICE))/as.numeric(gsub(",","",data[data$YEAR <= 2020, ]$VEP))*100
data$Y[data$YEAR >= 2022] = as.numeric(gsub(",","",data[data$YEAR >= 2022, ]$TOTAL_BALLOTS_COUNTED))/as.numeric(gsub(",","",data[data$YEAR >= 2022, ]$VEP))*100
data$Y = as.numeric(data$Y)
names(data)[names(data)=="Law"] <- "W"
names(data)[names(data)=="STATE"] <- "State"
names(data)[names(data)=="YEAR"] <- "Year"




data$W = as.numeric(data$W)

#create early vs late adopting groups
data$group = as.numeric(data$State %in% c("Arizona", "Georgia", "Indiana", "Ohio")) + 2*as.numeric(data$State %in% c("Alabama", "Kansas", "Mississippi", "North Dakota", "Tennessee", "Virginia", "Wisconsin", "Wyoming", "New Hampshire"))

#synthetic difference-in-differences requires these column names
data$Unit = data$State
data$Time = data$Year

all_sdid_2224 = StaggeredSynthDiD(data[data$State != "North Dakota",],vcov="jack")
presidential_sdid_2224 = StaggeredSynthDiD(data[as.numeric(data$Year)%%4 == 0 & data$State != "North Dakota",],vcov="jack")
midterm_sdid_2224 = StaggeredSynthDiD(data[as.numeric(data$Year)%%4 == 2,],vcov="jack")
all_early_sdid_2224 <- StaggeredSynthDiD( data[ data$group != 2,],vcov="jack")
presidential_early_sdid_2224 <- StaggeredSynthDiD( data[as.numeric(data$Year)%%4 == 0& data$group != 2,],vcov="jack")
midterm_early_sdid_2224 <- StaggeredSynthDiD( data[as.numeric(data$Year)%%4 == 2& data$group != 2,],vcov="jack")
all_late_sdid_2224 <- StaggeredSynthDiD( data[ data$group != 1 & data$State != "North Dakota",],vcov="jack")
presidential_late_sdid_2224 <- StaggeredSynthDiD( data[as.numeric(data$Year)%%4 == 0& data$group != 1 & data$State != "North Dakota",],vcov="jack")
midterm_late_sdid_2224 <- StaggeredSynthDiD( data[as.numeric(data$Year)%%4 == 2& data$group != 1,],vcov="jack")
